# -*- coding: UTF-8 -*-

from utils.log_util.LoggerUtil import get_logger
import pymysql
from utils.Constants import *

log = get_logger(__name__)

# mysql参数配置
mysql_host = mysql_host
mysql_user = mysql_user
mysql_password = mysql_password
mysql_port = mysql_port
mysql_db = mysql_db
mysql_use_unicode = mysql_use_unicode
mysql_encode = mysql_encode


# 链接数据库
def connect_db(host, port, user, password, db, **kwargs):
    log.info('---MySQL_CONNECTING---连接到mysql服务器...---MySQL_CONNECTING---')
    db = pymysql.connect(
        host=mysql_host if host is None else host,
        port=mysql_port if port is None else port,
        user=mysql_user if user is None else user,
        passwd=mysql_password if password is None else password,
        db=mysql_db if db is None else db,
        charset=mysql_encode if kwargs.get('encode') is None else kwargs.get('encode'))
    log.info("---MySQL_CONNECTED---数据库已连接---MySQL_CONNECTED---")
    return db


# 获取游标
def get_cursor(db):
    return db.cursor()


# 关闭数据库连接
def close_db(db):
    db.close()


# 增删改方法
def crud(sql):
    log.debug("---MySQL_SQL---准备执行的SQL语句： " + sql)

    db = connect_db()
    cursor = get_cursor(db)

    try:
        cursor.execute(sql)
        db.commit()
    except:
        db.rollback()
        log.error("---MySQL_ERROR---数据库操作失败！！！---MySQL_ERROR---")
    finally:
        close_db(db)
        log.info("---MySQL_SUCCESSED---数据库操作成功！---MySQL_SUCCESSED---")


# 查询方法
def select(sql):
    log.debug("---MySQL_SQL---准备执行的SQL语句： " + sql)

    db = connect_db()
    cursor = get_cursor(db)

    try:
        cursor.execute(sql)
        db.commit()
    finally:
        close_db(db)
